package com.wanshi.servlet;

import com.wanshi.dao.UserDao;
import com.wanshi.entity.User;
import com.wanshi.service.UserService;
import com.wanshi.utils.DateUtils;
import com.wanshi.utils.MD5Util;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/regist")
public class RegistServlet extends HttpServlet {

    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        ServletContext context = this.getServletContext();
        String picSavePath = (String) context.getAttribute("pic_save_path");


        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List<FileItem> fileItems = null;
        fileUpload.setFileSizeMax(1024*1014*5);
        Map<String,String> paramMap = new HashMap<>();
        StringBuffer buffer = new StringBuffer();
        try {

            fileItems = fileUpload.parseRequest(request);
            for (FileItem item:fileItems){



                if (item.isFormField() ){
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println(name+"---"+value);
                    if ("hobby".equalsIgnoreCase(name)){
                        buffer.append(value+",");
                    }else {
                        paramMap.put(name,value);
                    }

                       }else {
                    String name = item.getName();
                    if (name==null || name.trim().equals("")){
                        //response.getWriter().write("必须选择头像");
                       paramMap.put("picurl","");
                        continue;
                    }
                    String s = UUID.randomUUID().toString().replace("-", "");
                    int index = name.lastIndexOf(".");
                    String houzhui =name.substring(index);

                    String date = DateUtils.getFormatData();
                    File file = new File(picSavePath+date);
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    File fileName = new File(file,s+houzhui);
                    FileOutputStream fos=new FileOutputStream(fileName);
                    InputStream is = item.getInputStream();

                    byte[] bs=new byte[1024];
                    int len = 0;
                    while ((len=is.read(bs))!=-1){
                        fos.write(bs,0,len);
                    }
                    is.close();
                    fos.close();
                    paramMap.put("picurl",date+s+houzhui);
                    //response.getWriter().write("恭喜你文件上传成功");
                }
            }
            if (buffer.toString().length()==0){
                paramMap.put("hobby","hobby");
            }else {
                String hobby = buffer.substring(0,buffer.length()-1);
                paramMap.put("hobby",hobby);
            }

            User user =new User();
            BeanUtils.copyProperties(user,paramMap);

            HttpSession session = request.getSession();
            String ma = (String) session.getAttribute("ma");
            String yan =paramMap.get("yan");
        if(ma == null || !ma.equals(yan)){
            request.setAttribute("error","验证码错误");
            request.setAttribute("user",user);
            request.getRequestDispatcher("/regist.jsp").forward(request,response);
            return;
        }
            Map<String, String> errorMap = user.checkUser();
            if(errorMap.size() > 0){
                request.setAttribute("map",errorMap);
                request.setAttribute("user",user);
                request.getRequestDispatcher("/regist.jsp").forward(request,response);
                return;
            }
            user.setPassword(MD5Util.getMD5Str(user.getPassword()));


            if(userService.findUserByName(user.getUsername()) != null){
                //response.getWriter().write("该用户名已经存在!");
                request.setAttribute("error","该用户名已经存在!");
                request.setAttribute("user",user);
                request.getRequestDispatcher("/regist.jsp").forward(request,response);
            }else{

                //2 添加到数据库
                userService.addUser(user);
                response.getWriter().write("注册成功!3秒后跳转到首页");
                response.setHeader("refresh","3;url="+request.getContextPath()+"/index.jsp");
                //3 用户名不能重复
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

